# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import json
import oyaml as yaml

from sqlitedict import SqliteDict


def generate_runner_config(portfolio, max_pos, date, slots=None, merge_config=None):
  slots = slots or [
      '0.strategy-05.eu-west-1',
      '1.strategy-05.eu-west-1',
      '0.strategy-06.eu-west-1',
      '1.strategy-06.eu-west-1',
      '0.strategy-07.eu-west-1',
      '1.strategy-07.eu-west-1',
      '0.strategy-08.eu-west-1',
      '1.strategy-08.eu-west-1',
      '0.strategy-09.eu-west-1',
      '1.strategy-09.eu-west-1',
      '0.strategy-10.eu-west-1',
      '1.strategy-10.eu-west-1',
      '0.strategy-11.eu-west-1',
      '1.strategy-11.eu-west-1',
      '0.strategy-12.eu-west-1',
      '1.strategy-12.eu-west-1',
      '0.strategy-14.eu-west-1',
      '1.strategy-14.eu-west-1',
      '0.strategy-15.eu-west-1',
      '1.strategy-15.eu-west-1'
  ]
  assert len(portfolio) <= len(slots), portfolio

  config = merge_config or {
      'default': {
          'entrypoint': 'coin/strategy/mm/bitmex/pass_unhedge_2.py', 'period_min': 30
      }
  }

  date_str = date.strftime('%Y%m%d')

  # Convert '30m.09bp.09bp.12stack' to
  # 'pass_unhedge.xbtusd.btc-quarter.30m.09bp.09bp.12stack.9000'

  for idx, param in enumerate(portfolio):
    ma_window = int(param[0:2])
    stack = int(param[14:16])

    # Decide lot_size
    half_stack = stack // 2
    lot_size = max_pos // half_stack

    slot = slots[idx]
    config[slot] = {
        'cmd': ('pass_unhedge.xbtusd.btc-quarter.%s.%d --tag=%s' % (param, lot_size, date_str)),
        'warming_up_min': ma_window
    }

  return config


def generate_runner_config_from_portfolio_db(portfolio_db,
                                             date,
                                             max_pos,
                                             check_num_portfolio=None,
                                             dump_yaml_filepath=None,
                                             **kwargs):
  date_str = date.strftime('%Y%m%d')
  with SqliteDict(portfolio_db,
                  tablename='portfolio',
                  flag='r',
                  encode=json.dumps,
                  decode=json.loads) as table:
    portfolio = table[date_str]

  if check_num_portfolio is not None:
    assert len(portfolio) == check_num_portfolio, portfolio

  config = generate_runner_config(portfolio, max_pos, date, **kwargs)
  if dump_yaml_filepath:
    config_yaml = yaml.dump(config, default_flow_style=False)
    with open(dump_yaml_filepath, 'w') as f:
      f.write(config_yaml)

  return config
